'use strict';

const Service = require('egg').Service;
class Project extends Service {
    
    async list(params){
        const { ctx } = this;

        let pageSize = parseInt(params.page_size) || 10;
        let page = parseInt(params.page) || 1;
        let offset = (page - 1) * pageSize;
        
        let {count, rows} = await ctx.model.Project.findAndCountAll({
            limit: pageSize,
            offset: offset,
            order: [["sn", 'desc']]
        });
        return {
            list: rows,
            count: count
        };
    }

    async getDoingList(){
        const { ctx } = this;
        
        let list = await ctx.model.Project.findAll({
            where: {
                status: 1
            },
            order: [["sn", 'desc']]
        })

        return list;
    }

    async getProjectName(projectId){
        let info = await this.getProject(projectId);

        return info? info.name : "";
    }

    async getProject(projectId){
        const { ctx }  = this;
        let ck = "cache_projectInfo_" + projectId; 
        let info = await ctx.service.cache.get(ck);

        if(!info){
            info = await ctx.model.Project.findOne({
                where: {
                    id: projectId
                }
            })

            await ctx.service.cache.set(ck, info, 120)
        }

        return info;
    }

    async save(data){
        const { ctx } = this;

        let rs = null;
        if(data.id){
            rs = await ctx.model.Project.update(data, {where:{id: data.id}});
        } else {
            data.create_user_id = ctx.user.id;
            rs = await ctx.model.Project.create(data);
        }
        return rs;
    }

    async del(id){
        const { ctx } = this;

        var rs = await ctx.model.Project.destroy({where : {id: id}});

        return rs;
     }
    
}

module.exports = Project;